#pragma once

#include <QOpenGLWidget>
#include <QOpenGLFunctions_4_5_Core>
#include <QVector>
#include <QOpenGLShaderProgram>
#include <QDebug>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
#include <QImage>
#include <QImageReader>
#include <QOpenGLTexture>
#include <QMatrix4x4>
#include <QMouseEvent>
#include <QtCore/QtMath>
#include <QVector>
#include <QSettings>

class OpenglWidget : public QOpenGLWidget, protected QOpenGLFunctions_4_5_Core
{
    Q_OBJECT
public:
    OpenglWidget(QWidget *parent = nullptr);
    ~OpenglWidget();
    virtual void initializeGL() override;
    virtual void paintGL() override;
    virtual void resizeGL(int w, int h) override;

protected:
    virtual void mouseMoveEvent(QMouseEvent *event) override;
    virtual void mousePressEvent(QMouseEvent *event) override;
    virtual void mouseReleaseEvent(QMouseEvent *event) override;
    virtual void wheelEvent(QWheelEvent *event) override;
public slots:
    void setImage(QImage &image);

signals:
    void loadImagFilsh();

private:
    QOpenGLShaderProgram shader;
    QOpenGLVertexArrayObject vao;
    QOpenGLBuffer vbo;
    QOpenGLTexture texture{QOpenGLTexture::Target2D};
    QMatrix4x4 projection;
    QMatrix4x4 view;
    QMatrix4x4 model;

    QPoint lastMousePos;
    bool isLeftButtonPressed = false;
    // 相机控制参数
    QVector3D cameraPos{0.0f, 0.0f, 0.0f};
    QVector3D cameraFront{0.0f, 0.0f, -1.0f};
    QVector3D cameraUp{0.0f, 1.0f, 0.0f};
    float yaw = -90.0f; // 偏航角
    float pitch = 0.0f; // 俯仰角
    float fov = 90.0f;  // 视场角

    QSettings sets;

    // float mouseSensitivity = 0.0015;
    // float mouseFov = 4.0;

    // 立方体顶点数据（中心在原点，边长2，覆盖[-1,1]范围）
    QVector<float>
        vertices = {
            // 位置
            -1.0f, 1.0f, -1.0f,
            -1.0f, -1.0f, -1.0f,
            1.0f, -1.0f, -1.0f,
            1.0f, -1.0f, -1.0f,
            1.0f, 1.0f, -1.0f,
            -1.0f, 1.0f, -1.0f,

            -1.0f, -1.0f, 1.0f,
            -1.0f, -1.0f, -1.0f,
            -1.0f, 1.0f, -1.0f,
            -1.0f, 1.0f, -1.0f,
            -1.0f, 1.0f, 1.0f,
            -1.0f, -1.0f, 1.0f,

            1.0f, -1.0f, -1.0f,
            1.0f, -1.0f, 1.0f,
            1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, -1.0f,
            1.0f, -1.0f, -1.0f,

            -1.0f, -1.0f, 1.0f,
            -1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f,
            1.0f, -1.0f, 1.0f,
            -1.0f, -1.0f, 1.0f,

            -1.0f, 1.0f, -1.0f,
            1.0f, 1.0f, -1.0f,
            1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f,
            -1.0f, 1.0f, 1.0f,
            -1.0f, 1.0f, -1.0f,

            -1.0f, -1.0f, -1.0f,
            -1.0f, -1.0f, 1.0f,
            1.0f, -1.0f, -1.0f,
            1.0f, -1.0f, -1.0f,
            -1.0f, -1.0f, 1.0f,
            1.0f, -1.0f, 1.0f};
};
